using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.ElectronicSign;
using NP.Enterprise.Utils.Http;
using RestSharp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using static NP.BPMReportPlatform.Contract.Dtos.ContractEnum;
using static NP.BPMReportPlatform.ElectronicSign.ESDto;
using System.Security.Policy;
using Elasticsearch.Net;
using NP.BPMReportPlatform.WordHelper;
using NP.BPMReportPlatform.Contract;
using NP.BPMReportPlatform.ElectronicSign.Dto;
using NP.BPMReportPlatform.Entities.BPM_Business.ESign;
using Org.BouncyCastle.Asn1.BC;
using System.Diagnostics.Contracts;
using Serilog;
using NP.BPMReportPlatform.Entities.BPM_Business;
using MiniSoftware;
using NP.BPMReportPlatform.Leave.Dto;
using static NP.BPMReportPlatform.Leave.Dto.LeaveDto;
using System.Text.RegularExpressions;

namespace NP.BPMReportPlatform.SF
{
    /// <summary>
    /// Risk接口(简称Risk)
    /// </summary>
    public class RiskService : BPMReportPlatformAppService, IRiskService
    {
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly string _initiatorAccountId;
        private readonly string _esbUrl;
        private ILogger _logger;

        /// <summary>
        /// 电子签接口入口
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        /// <param name="httpClient"></param>
        /// <param name="configuration"></param>
        public RiskService(ISqlSugarAppService sqlSugarAppService,
            INPRestHttpHelper httpClient, IConfiguration configuration,
            ILogger logger)
        {
            _nPRestHttp = httpClient;
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _esbUrl = configuration["Nippon:ESB:ESBCommApi"];
            _logger = logger;
        }

        #region 01 Risk推送

        /// <summary>
        /// 发起Risk
        /// </summary>
        /// <returns></returns>
        public async Task<string> CreateRisk(string businessCode)
        {
            string result = await CreateRiskForCertification(businessCode);
            return result;
        }

        /// <summary>
        /// 发起Risk推送
        /// </summary>
        /// <param name="businessCode">单据编码</param>
        /// <returns></returns>
        private async Task<string> CreateRiskForCertification(string businessCode)
        {

            StringBuilder log = new StringBuilder();
            log.AppendLine($"-----Risk接口：CreateRiskForCertification   开始----{businessCode}");

            var entity = await _db.Queryable<EmpCertificationEntity>().Where(t => t.InstanceNumber == businessCode).FirstAsync();

            if (entity == null || entity.SealType != "鲜章" && entity.SealType != "鲜章纸质版" && entity.SealType != "鲜章电子版")
            {
                return string.Empty;
            }

            var user = _dbPlatform.Queryable<UserExtension>().Where(t => t.Sapemployeeid == entity.WorkNumber).First();
            if (user == null)
            {
                return string.Empty;
            }

            var corporate = _dbPlatform.Queryable<CorporateEntity>().Where(t => t.CorporateCode == user.Sapcompanycode).First();
            if (corporate == null || string.IsNullOrEmpty(corporate.SealCode))
            {
                entity.RiskPushStatus = "未推送";
                entity.RiskPushErrorMsg = "法人公司数据有误，请检查";
                _db.Updateable(entity).UpdateColumns(t => new { t.RiskPushStatus, t.RiskPushErrorMsg }).ExecuteCommand();
                return string.Empty;
            }

            var er = _dbPlatform.Queryable<UserExtension>().Where(t => t.Name == entity.ErName && t.Email == entity.ErEmail).First();
            if (entity.CertTypeName == "薪资证明")
            {
                er = _dbPlatform.Queryable<UserExtension>().Where(t => t.Name == entity.XzName && t.Email == entity.XzEmail).First();
            }

            try
            {
                // 请假信息推送给SAP
                Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                { "serviceName", "S_XXX_RISK_BpmSendRiskYGZM_S" },
                { "sourceSystem", "BPMNEW" },
            };

                // TODO:推送Risk
                var requestBody = new
                {
                    BpmId = entity.InstanceNumber,
                    BpmCode = entity.InstanceNumber,
                    BpmName = $"{entity.UserName}的{entity.CertTypeName}",
                    CreatorID = er?.Sapemployeeid, // 员工关系专员工号
                    CreatorLoginname = er?.Loginname,// 员工关系专员账号
                    StaffName = entity.WorkNumber,// 员工姓名
                    StaffID = entity.UserName,// 员工姓名
                    YZBH = corporate.SealCode,
                    YYCS = "1"
                };

                var resultData = _nPRestHttp.ESBPostAsync(_esbUrl, requestBody, dic).Result;
                //var resultData = Regex.Unescape(resultData);
                var result = JsonConvert.DeserializeObject<RiskDto.UpdateResponseData>(resultData);
                if (result != null && result.code == 200)
                {
                    entity.RiskPushStatus = "推送成功";
                    entity.RiskPushErrorMsg = string.Empty;
                }
                else
                {
                    entity.RiskPushStatus = "推送失败";
                    entity.RiskPushErrorMsg = result.message;
                }
                _db.Updateable(entity).UpdateColumns(t => new { t.RiskPushStatus, t.RiskPushErrorMsg }).ExecuteCommand();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                log.AppendLine("-----Risk接口：CreateRiskForCertification   结束----");
                _logger.Error(log.ToString());
            }

            return entity.RiskCode;
        }

        #endregion

        #region 02 状态回调接口

        /// <summary>
        /// 电子签状态回调接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns>状态回调</returns>
        public async Task<RiskDto.UpdateResponseData> UpdateStatus(RiskDto.UpdateRequestData request)
        {
            RiskDto.UpdateResponseData result = new RiskDto.UpdateResponseData()
            {
                code = 200
            };
            StringBuilder log = new StringBuilder();
            log.AppendLine($"-----Risk接口：UpdateStatus   开始----");
            log.AppendLine($"入参：{JsonConvert.SerializeObject(request)}");

            try
            {
                var entity = await _db.Queryable<EmpCertificationEntity>().Where(t => t.InstanceNumber == request.BpmCode).FirstAsync();
                if (entity != null)
                {
                    entity.RiskCode = request.SQM;
                    entity.RiskPushStatus = "推送成功";
                    entity.RiskPushErrorMsg = string.Empty;
                    _db.Updateable(entity).UpdateColumns(t => new { t.RiskCode, t.RiskPushStatus, t.RiskPushErrorMsg }).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.message = ex.Message;
            }
            finally
            {
                log.AppendLine($"出参：{JsonConvert.SerializeObject(result)}");
                log.AppendLine("-----Risk接口：UpdateStatus   结束----");
                _logger.Error(log.ToString());
            }
            return result;
        }

        #endregion
    }
}
